local base = _G
local math = base.math
local table = base.table
local ipairs = base.ipairs
module("gui")

GraphG = {}
GraphGMT = { __index = GraphG }

base.setmetatable(GraphG, { __index = ObjectG })

GraphG.create = function(x, y, width, height, type, mt)
  local styles = get_styles('padding')
  local colors = get_colors('background', 'item')

  local self = Object(x, y, width, height, mt or GraphGMT)

  self.styles = styles
  self.colors = colors

  self.type = type
  self.values = {}

  return self
end

GraphG.destroy = function(self)
  self.type = nil
  self.values = nil
  ObjectG.destroy(self)
end

GraphG.redraw = function(self, delta)
  local min, max = self.values[1], self.values[1]
  for i, v in ipairs(self.values) do
    min = math.min(v, min)
    max = math.max(v, max)
  end
  local range
  if max and min then
    range = max - min
  end
  
  local c = self.sprite.canvas
  c:clear()

  -- draw background rectangle
  local l, t, r, b = 0, -self.height, self.width, 0
  c:rect(l, t, r, b)
  c:set_fill_style(self.colors.background, 1)
  c:fill()

  local pad = self.styles.padding
  local w = self.width - pad*2
  local h = self.height - pad*2
  local bar = w/#self.values
  for i, v in ipairs(self.values) do
    local y =(v - min)/range*h
    c:move_to((i - 1)*bar + pad + bar/2, -h - pad + y/2)
    c:rectangle(bar - 1, y + 1)
  end
  c:set_fill_style(self.colors.item, 1)
  c:fill()
end

GraphG.update = function(self, dt)
  self:redraw(dt)
end

Graph = GraphG.create